//
//  NRWCarBuyCarsController.m
//  New_Runway
//
//  Created by mack on 2018/1/24.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarBuyCarsController.h"
#import "NRWCarCarListCell.h"
#import "NRWCarHomeBannerModel.h"
#import "NRWCarHomeNoticeModel.h"
#import "NRWCarListsModel.h"
#import "CarDetailMainVC.h"
#import "BuyCarTopview.h"

#import "DefaultSortView.h"
#import "AllKindOfCarVC.h"
#import "SectionSliderVC.h"
#import "CarFilterVC.h"

#import "BuyCarDetailVC.h"
#import "BuyCarMarketVC.h"

@interface NRWCarBuyCarsController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (assign, nonatomic) NSInteger pageNo;
@property (nonatomic, strong) NSMutableArray *carArray;
@property (nonatomic, strong) BuyCarTopview *topview;
@property (nonatomic, strong) NSMutableDictionary *params;
@property (nonatomic, strong) DefaultSortView *defaultView;
@property (nonatomic, assign) BOOL isShow;
@property (nonatomic, strong) NSIndexPath *seleIndex;
@property (nonatomic, strong) NSIndexPath *modelSeleIndexPath;
@property (nonatomic, strong) NSIndexPath *seriesSeleIndexPath;
@property (nonatomic, strong) NSIndexPath *marketSeleted;
@property (nonatomic, strong) NSMutableDictionary *filterDic;
@property (nonatomic, strong) NSMutableDictionary *indexDic;
@property (nonatomic, assign) BOOL isWhich;
@property (nonatomic, copy) NSString *fromPrice;
@property (nonatomic, copy) NSString *toPrice;
@end

@implementation NRWCarBuyCarsController
-(NSMutableDictionary *)indexDic{
    if (!_indexDic) {
        _indexDic = [[NSMutableDictionary alloc] init];
    }
    return _indexDic;
}
-(NSMutableArray *)carArray{
    if (!_carArray) {
        _carArray = [[NSMutableArray alloc] init];
    }
    
    return _carArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.fromPrice = self.toPrice = @"";
    self.navigationBarView.titleLabel.text = @"买车";
//    [self.navigationBarView.rightItem setTitle:@"重置" forState:UIControlStateNormal];
    self.navigationBarView.leftItem.hidden = YES;
    self.pageNo = 1;
    [self initTableview];
    [self setdicValueForKey];
    [self.view addSubview:self.topview];
    self.isShow = NO;
    [self.view addSubview:self.defaultView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(brandSearch:)name:@"BrandSearch" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(seleletedKindOfCarIndexPath:)name:@"SELEINDEXPATH" object:nil];
    [self.indexDic setObject:@(INTMAX_MAX) forKey:@"threeIndex"];
    [self.indexDic setObject:@(INTMAX_MAX) forKey:@"fourIndex"];
    [self.indexDic setObject:@(INTMAX_MAX) forKey:@"fiveIndex"];

}
//-(void)rightItemClick{
//    [self setdicValueForKey];
//}
//
-(void)setdicValueForKey{
    
    _params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@(1),@"marketId",@(15),@"pageSize",@(self.pageNo),@"pageIndex",@(20),@"carSaleState",@"DESC",@"orderMode",@"CAR_SALE_TIME",@"orderColunm",nil];
    [self loadCarList];
    self.seleIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    self.modelSeleIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.seriesSeleIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.marketSeleted = nil;
    [self.defaultView updateSelected];

}

-(BuyCarTopview *)topview{
    
    if (!_topview) {
        _topview = [[[NSBundle mainBundle] loadNibNamed:@"BuyCarTopview" owner:self options:nil]lastObject];
        [_topview.filterButton setTitle:@"市场" forState:UIControlStateNormal];
        kSelfWeak;
        _topview.Clickback = ^(NSInteger index) {
            
            if (index == 1) {
                weakSelf.isShow = !weakSelf.isShow;
                [weakSelf defaultViewAnimation:weakSelf.isShow];
            }else if (index == 2){
                AllKindOfCarVC *carVC = [[AllKindOfCarVC alloc] init];
                carVC.isDesk = NO;
                carVC.Allback = ^(NSIndexPath *index) {
                    [weakSelf.params removeObjectForKey:@"brandId"];
                    [weakSelf.params removeObjectForKey:@"modelId"];
                    [weakSelf.params removeObjectForKey:@"seriesId"];
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];

                    [weakSelf loadCarList];
                    weakSelf.seleIndex = index;
                };
                carVC.selectedIndexPath = weakSelf.seleIndex;
                carVC.modelSeleIndexPath = weakSelf.modelSeleIndexPath;
                carVC.seriesSeleIndexPath = weakSelf.seriesSeleIndexPath;
                [weakSelf.navigationController pushViewController:carVC animated:YES];
            }else if (index == 3){
                SectionSliderVC *sliderVc = [[SectionSliderVC alloc] init];
                sliderVc.block = ^(NSString *fromPrice, NSString *toPrice, BOOL isWhich) {
                    [weakSelf.params setObject:fromPrice forKey:@"fromRetailPrice"];
                    [weakSelf.params setObject:toPrice forKey:@"toRetailPrice"];
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
                    [weakSelf loadCarList];
                    weakSelf.isWhich = isWhich;
                    weakSelf.fromPrice = fromPrice;
                    weakSelf.toPrice = toPrice;
                };
                sliderVc.isWhich = weakSelf.isWhich;
                sliderVc.fromPrice = weakSelf.fromPrice;
                sliderVc.toPrice = weakSelf.toPrice;
                
                [weakSelf.navigationController pushViewController:sliderVc animated:YES];
                
            }else if (index == 4){
            
                CarFilterVC *filterVC = [[CarFilterVC alloc] init];
                filterVC.isBuyCar = YES;
                filterVC.searchBlock = ^(NSMutableDictionary *searchDic, NSMutableDictionary *indexPathDic) {
                    weakSelf.filterDic = searchDic;
                    weakSelf.indexDic = indexPathDic;
                    [weakSelf.params addEntriesFromDictionary:searchDic];
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
                    [weakSelf loadCarList];
                };
                filterVC.allDataDic = weakSelf.filterDic;
                filterVC.selectedDic = weakSelf.indexDic;
                [weakSelf.navigationController pushViewController:filterVC animated:YES];
            }else if (index == 5){
                
                BuyCarMarketVC *marketvc = [[BuyCarMarketVC alloc] init];
                marketvc.MarketBlock = ^(NSString *marketId, NSIndexPath *index){
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
                    [weakSelf.params setObject:marketId forKey:@"marketId"];
                    [weakSelf loadCarList];
                    weakSelf.marketSeleted = index;
                };
                marketvc.selIndex = weakSelf.marketSeleted;
                [weakSelf.navigationController pushViewController:marketvc animated:YES];
                
            }
            
        };
        _topview.frame = CGRectMake(0, self.navH, Screen_width, 40);
        _topview.layer.shadowOpacity = 0.3;
       _topview.layer.shadowColor = [UIColor grayColor].CGColor;
       _topview.layer.shadowRadius = 3;
       _topview.layer.shadowOffset = CGSizeMake(1,1);
        [self.navigationBarView bringSubviewToFront:self.view];
    }
    return _topview;
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarCarListCell" bundle:nil] forCellReuseIdentifier:@"NRWCarCarListCell"];
    self.tableview.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
    self.tableview.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoadMore)];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH + 40);
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.tabH);
        make.left.right.equalTo(weakSelf.view);
    }];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 110;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.carArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NRWCarCarListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarCarListCell"];
    cell.isBuyCar = YES;
    cell.carModel = self.carArray[indexPath.row];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    Result *rt = self.carArray[indexPath.row];
    BuyCarDetailVC *detailVC = [[BuyCarDetailVC alloc] init];
    detailVC.carID = rt.carId;
    detailVC.carModel = rt;
    detailVC.isHistory = NO;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}

-(void)downPullRefresh{
    self.pageNo = 1;
    [_params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCarList];
}
-(void)upPullLoadMore{
    self.pageNo += 1;
    [_params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCarList];
    
}


-(void)loadCarList{
    
    
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,carListsApi] refreshRequest:YES cache:NO params:_params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if (self.pageNo == 1) {
            [self.carArray removeAllObjects];
        }
      
        NSArray *noticeArr = response[@"result"];
        for (NSDictionary *dic in noticeArr) {
            Result *rt = [Result mj_objectWithKeyValues:dic];
            [self.carArray addObject:rt];
        }
        if (self.carArray.count == 0) {
            [self.tableview addDefaultViewWithText:@"暂时没有数据哦！" defaultImageType:DefaultImageTypeNoData];
            
        }else{
            [self.tableview removeDefaultView];
        }
        
        [self.tableview reloadData];
        [self endRefresh];
        [SVProgressHUD dismiss];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [self endRefresh];
        [SVProgressHUD dismiss];

    }];    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
    
}
-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
    
}

-(DefaultSortView *)defaultView{
    if (!_defaultView) {
        _defaultView = [[DefaultSortView alloc] init];
        _defaultView.type = kBuyCar;
        _defaultView.frame = CGRectMake(0, self.navH + 40, Screen_width, 0);
        _defaultView.userInteractionEnabled = YES;
        UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
        PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
        PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
        PrivateLetterTap.delegate = self;
        [_defaultView addGestureRecognizer:PrivateLetterTap];
        kSelfWeak;
        _defaultView.selectedBlock = ^(NSInteger index) {
            [weakSelf defaultViewAnimation:NO];
            weakSelf.isShow = NO;

            if (index == 0) {
             
                [weakSelf.params setValue:@"CAR_SALE_TIME" forKey:@"orderColunm"];
                [weakSelf.params setValue:@"DESC" forKey:@"orderMode"];

            }else if (index == 1){
                
                [weakSelf.params setValue:@"CAR_SALE_TIME" forKey:@"orderColunm"];
                [weakSelf.params setValue:@"ASC" forKey:@"orderMode"];
            }else if (index == 2){
                [weakSelf.params setValue:@"DESC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_RETAIL_PRICE" forKey:@"orderColunm"];

            }else if (index == 3){
                [weakSelf.params setValue:@"ASC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_RETAIL_PRICE" forKey:@"orderColunm"];

            }else if (index == 4){
                [weakSelf.params setValue:@"DESC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_LICENCE_DATE" forKey:@"orderColunm"];

            }else if (index == 5){
                [weakSelf.params setValue:@"ASC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_MILEAGE" forKey:@"orderColunm"];

            }
            weakSelf.pageNo = 1;
            [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];

            [weakSelf loadCarList];

        };
    }
    return _defaultView;
}
- (void)tapAvatarView: (UITapGestureRecognizer *)gesture{
    
    [self defaultViewAnimation:NO];
    self.isShow = NO;
    
}

-(void)defaultViewAnimation:(BOOL)isshow{
    if (isshow == YES) {
        _defaultView.frame = CGRectMake(0, self.navH + 40, Screen_width, Screen_height - self.navH - 40);

        [UIView animateWithDuration:0.5 animations:^{
          _defaultView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.4];
            _defaultView.tableview.frame = CGRectMake(0, 0, Screen_width, 300);
        } completion:^(BOOL finished) {
            
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            _defaultView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0];
            _defaultView.tableview.frame = CGRectMake(0, 0, Screen_width, 0);

        } completion:^(BOOL finished) {
            _defaultView.frame = CGRectMake(0, self.navH + 40, Screen_width, 0);

        }];
    }
   
}
-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    [self defaultViewAnimation:NO];
    self.isShow = NO;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }//否则手势存在
    return YES;
}
-(void)brandSearch:(NSNotification *)info{
    NSDictionary *dic = info.userInfo;
    [self.params setValue:dic[@"brandId"] forKey:@"brandId"];
    [self.params setValue:dic[@"seriesId"] forKey:@"modelId"];
    [self.params setValue:dic[@"modelId"] forKey:@"seriesId"];
    self.pageNo = 1;
    [self.params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCarList];
}
-(void)seleletedKindOfCarIndexPath:(NSNotification *)info{
    NSDictionary *dic = info.userInfo;
    self.seleIndex = dic[@"brandIndexPath"];
    self.modelSeleIndexPath = dic[@"modelIndexPath"];
    self.seriesSeleIndexPath = dic[@"seriesIndexPath"];
    
}
- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
}
@end
